package com.webserver_v2.core;

import com.webserver_v2.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;
    private static File rootDir;
    private static File staticDir;

    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    static {
        try {
            rootDir = new File( ClientHandler.class.getClassLoader()
                    .getResource(".").toURI());
           staticDir = new File(rootDir,"static");

        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    public void run(){
        try {
            //1.解析请求(读取浏览器发送的请求)
            HttpServletRequest request = new HttpServletRequest(socket);

            //2.处理请求(获取请求中的uri)
            String path = request.getUri();

            //3.发送响应
            File file = new File(staticDir,path);
            OutputStream out = socket.getOutputStream();

            //发送状态行
            println("HTTP/1.1 200 OK");

            //发送响应头
            println("Content-Type: text/html");
            println("Content-Length: "+file.length());

            //单独发送回车+换行表达响应头发送完毕
            println("");

            //发送响应正文(将index.html文件所有数据发送)
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[10240];
            int len;
            while ((len = fis.read(data))!=-1){
                out.write(data,0,len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private void println(String line) throws IOException {
        OutputStream  out = socket.getOutputStream();
        out.write(line.getBytes(StandardCharsets.ISO_8859_1));
        out.write(13);//回车
        out.write(10);//换行
    }
}
